/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 * @version 1.0
 */
package shop.controller.front.product;

import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.plugins.wxlogin.AccessToken;
import shop.core.plugins.wxlogin.WxContainer;
import shop.core.plugins.wxlogin.WxUrlType;
import shop.core.plugins.wxlogin.WxUtil;
import shop.core.util.QRcodeUtils;
import shop.core.util.StrUtils;
import shop.services.front.members.MembersService;
import shop.services.front.members.bean.Members;
import shop.services.front.product.ProductService;
import shop.services.front.product.bean.Product;
import shop.services.front.spec.SpecService;
import shop.services.front.spec.bean.Spec;
import shop.services.front.systemSetting.SystemSettingService;
import shop.services.front.systemSetting.bean.SystemSetting;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名称：ProductController
 * @创建人：Ltz
 * @创建时间：2017-09-20 下午15:50:43
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/front/product/")
public class ProductController extends FrontBaseController<Product> {
    @Resource
    private ProductService productService;
    @Resource
    private SpecService specService;
    @Resource
    private UserService userService;
    @Resource
    private SystemSettingService systemSettingService;
    @Resource
    private MembersService membersService;
    @Override
    public Services<Product> getService() {
        return productService;
    }

    /**
     * 跳转到商城首页（列表）
     *
     * @return
     */
    @RequestMapping("toProductList")
    public String toProductList() {
        return "/front/index";
    }

    /**
     * 跳转到商品分类详情页面（列表）
     *
     * @return
     */
    @RequestMapping("toCatalogDetail")
    public String toCatalogDetail() {
        return "/front/catalog/catalogList";
    }

    /**
     * 跳转到商品详情页面
     *
     * @return
     */
    @RequestMapping("toProductDetail")
    public String toProductDetail() {
        return "/front/product/productDetail";
    }

    /**
     * 跳转到发现页面
     *
     * @return
     */
    @RequestMapping("toAbout")
    public String toAbout() {
        return "/front/find/findList";
    }

    /**
     * 跳转到加入我们页面
     *
     * @return
     */
    @RequestMapping("toJoin")
    public String toJoin() {
        return "/front/find/findJoin";
    }


    /**
     * 微信授权登陆
     * @return
     */
    @RequestMapping(value = "toWx", method = RequestMethod.GET)
    public String toWx(HttpServletRequest request) {
        String pid=request.getParameter("pid");
        String appidUrl = "?appid=wx0955e62e5ce90320&";
        String redirect_uri = "redirect_uri=http://www.etexian.cn/rest/front/product/callBack";
        String typeUrl = "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        if(!org.apache.commons.lang.StringUtils.isBlank(pid)){
            redirect_uri=redirect_uri+"?pid="+pid;
        }
        return "redirect:" + WxUrlType.authorizeUrl + appidUrl + redirect_uri + typeUrl;
    }

    /**
     * 微信回调方法
     * @param request
     * @return
     */
    @RequestMapping(value = "callBack", method = RequestMethod.GET)
    public String callBack(HttpSession session, HttpServletRequest request) {
        String pid=request.getParameter("pid");
        String code=request.getParameter("code");
        Map<String,String> params=new HashMap<>();
        params.put("appid", WxContainer.appid);
        params.put("secret",WxContainer.secret);
        params.put("code",code);
        params.put("grant_type","authorization_code");
        AccessToken accessToken= WxUtil.sendRequest(WxUrlType.accessTokenUrl, HttpMethod.GET, params, null, AccessToken.class);
        Map<String,String> getUserInfoParams = new HashMap<>();
        getUserInfoParams.put("access_token",accessToken.getAccess_token());
        getUserInfoParams.put("openid",accessToken.getOpenid());
        getUserInfoParams.put("lang","zh_CN");
        Map<String,String> r=WxUtil.sendRequest(WxUrlType.userInfoUrl,HttpMethod.GET,getUserInfoParams,null,Map.class);
        logger.debug("微信登陆返回信息："+r);
        String openID=accessToken.getOpenid();
        logger.debug("userOpenId："+openID);
        session.setAttribute("userOpenId",openID);
        User user=userService.selectByOpenId(accessToken.getOpenid());
        if(user != null){
            session.setAttribute("userInfo",user);
            return "redirect:/rest/front/product/toProductList";
        }else{
            User rs=new User();
            rs.setOpenID(r.get("openid"));
            rs.setNickname(r.get("nickname"));
            rs.setSex(String.valueOf(r.get("sex")));
            rs.setIcon(r.get("headimgurl"));
            String username = StrUtils.getUUID();
            String password = StrUtils.getUUID();
            rs.setUsername(username);
            rs.setPassword(password);
            if(!org.apache.commons.lang.StringUtils.isBlank(pid)){
                rs.setPid(pid);
            }
            userService.insert(rs);
            QRcodeUtils qrCodeUtils = new QRcodeUtils();
            String contents="http://www.etexian.cn/rest/front/product/toWx?pid=" +rs.getId();
            rs.setQrCode(qrCodeUtils.createQrcode(request, contents));
            userService.update(rs);
            session.setAttribute("userInfo",rs);
            return "redirect:/rest/front/product/toProductList";
        }
    }

    /**
     * 查询佰信恒通介绍页
     * @param
     * @return
     */
    @RequestMapping(value = "selectAbout", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectAbout() {
        SystemSetting setting = systemSettingService.selectOne(new SystemSetting());
        jsonResult = new JSONResult();
        jsonResult.setData(setting);
        return jsonResult;
    }

    /**
     * 加入我们方法
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "insertMember", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertMember(HttpServletRequest request,Members members) throws Exception {
        User user = (User) request.getSession().getAttribute("userInfo");
        members.setUserID(user.getId());
        jsonResult = new JSONResult();
        membersService.insert(members);
        return jsonResult;
    }


    /**
     * 查询商品列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectProductList")
    @ResponseBody
    public JSONResult selectProductList(HttpServletRequest request, @ModelAttribute("product") Product product) throws Exception {
        jsonResult = new JSONResult();
        List<Product> rsList = productService.selectProductList(product);
        for(int i=0;i<rsList.size();i++){
            Spec spec =new Spec();
            spec.setProductID(rsList.get(i).getId());//获取rsList的第i+1个元素
            List<Spec> specList=specService.selectList(spec);
            rsList.get(i).setSpecs(specList);//把字段specs存入商品
        }
        jsonResult.setData(rsList);
        logger.debug("商品列表："+rsList);
        return jsonResult;
    }

    /**
     * 查询商品详情
     * @param product
     * @return
     */
    @RequestMapping(value="selectProductDetail",method=RequestMethod.GET)
    @ResponseBody
    public JSONResult selectProductDetail(Product product){
        JSONResult jsonResult=new JSONResult();
        Product rs=productService.selectOne(product);
        //查询产品规格库存列表
        Spec spec =new Spec();
        spec.setProductID(product.getId());
        List<Spec> specs=specService.selectList(spec);
        rs.setSpecs(specs);
        jsonResult.setData(rs);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 查询订单详情（商品详情入口）
     * @param spec
     * @return
     */
    @RequestMapping(value = "selectOrderDetail", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderDetail(Spec spec) {
        jsonResult = new JSONResult();
        spec =  specService.selectOne(spec);
        jsonResult.setData(spec);
        return jsonResult;
    }
}
